<?php
/**
 * Created by PhpStorm.
 * User: Jason.Jiang
 * Date: 2015/9/18
 * Time: 11:42
 */

class Controller
{

    public $controller_name = '';
    public $controller_upper = '';
    public $controller_folder = '';

    private $controller_template = '';
    private $controller_variable = '{$controller_name}';
    private $column;

    public function __construct($controller, $columns)
    {
        $this->controller_name = strtolower($controller);
        $this->controller_upper = ucfirst($this->controller_name);
        $this->controller_folder = PROJECT_PATH . DS . 'application' . DS . 'controllers';
        $this->controller_template = MODULE . DS . 'controller' . DS . 'controller.template.html';
        $this->column = $columns;
        $this->run();
    }

    public function run()
    {
        $data_str = $this->mkColumn();
        $controller_template = @file_get_contents($this->controller_template);
        $controller_con = str_replace(array($this->controller_variable,'{$data_str}'), array($this->controller_upper,$data_str), $controller_template);
        $controller_path =  $this->controller_folder . DS .$this->controller_name . '.php';
        @file_put_contents($controller_path, $controller_con);
    }

    public function mkColumn()
    {
        if(!$this->column)
        {
            return false;
        }

        if(!is_array($this->column) || !is_array($this->column))
        {
            return false;
        }

        $result_str = '';
        foreach($this->column as $val)
        {
            if($val != 'ctime')
            {
                $result_str .= "\$save_data['{$val}'] = \$this->input->post('{$val}');" . PHP_EOL . "            ";
            }
        }

        return $result_str;
    }
}